<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use EasyWeChat\Factory;
use think\Db;
use think\Request;
use think\Config;
use app\common\model\ScoreLog;

/**
 * 小程序登录
 */
class Wechat extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
	protected $appid;
    protected $appsecret;
    protected $mini_appid;
    protected $mini_appsecret;
    protected $config;
    protected $wxapp;
    protected $wechatapp;

    public function _initialize()
    {
        parent::_initialize();
        $this->mini_appid = Config::get('site.mini_appid');
        $this->mini_appsecret = Config::get('site.mini_appsecret');
        $this->config = [
            'app_id' => Config::get('site.mini_appid'),
            'secret' => Config::get('site.mini_appsecret'),
            'token' => 'easywechat',
            'aes_key' => '',
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ];
        $this->wxapp = Factory::miniProgram($this->config);
    }

    /**
     * 小程序登录第一步
     */
    public function session_key()
    {
        $code = input('code');
        $decryptSession = $this->wxapp->auth->session($code);
        //file_put_contents('log/weixin_login_notify.txt', json_encode($decryptSession) . "\r\n", FILE_APPEND);
        if(!isset($decryptSession['session_key'])){
            $this->error('未获取到session_key,请重启应用');
        }
        cache($decryptSession['session_key'], $decryptSession, 24*3600);
        $this->success('获取session_key',$decryptSession);
    }
    /**
     * 小程序登录第二步
     */
    public function login(){
        $params = $this->request->post();
        //file_put_contents('log/weixin_login_notify.txt', json_encode($params) . "\r\n", FILE_APPEND);
        extract($params);
        if(empty($iv)||empty($sessionKey)||empty($encryptedData)){
            $this->error('缺少必要参数');
        }
        if(empty($referrer_id)) $referrer_id=0;
        $referrer_id = (int)$referrer_id;

        $decryptSession = cache($sessionKey);
        if (!$decryptSession || !isset($decryptSession['openid'])) {
            $this->error('未获取到登录态,请重试!');
        }
        //file_put_contents('log/weixin_login_notify.txt', json_encode($decryptSession) . "\r\n", FILE_APPEND);
        $decryptUserInfo = $this->wxapp->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        $decryptUserInfo = array_merge($decryptUserInfo,$decryptSession);

        //组装decryptData
        $decryptData = array_change_key_case($decryptUserInfo, CASE_LOWER); // 将数组中的所有键名修改为小写
        if (empty($decryptData['openid'])) {
            $this->error('code错误,请重试!');
        }
        //file_put_contents('log/weixin_login_notify.txt', json_encode($decryptData) . "\r\n", FILE_APPEND);
        $result['miniopenid'] = $decryptData['openid'];
        $result['unionid'] = isset($decryptData['unionid'])?$decryptData['unionid']:'';
        $result['nickname'] = base64_decode(base64_encode($decryptData['nickname']));
        $result['avatar'] = $decryptData['avatarurl'];
        $extend['uniquecode'] = \app\common\model\User::unique_code();
        $loginret = \addons\third\library\Service::connect1('wechat', $result,$extend);
        if ($loginret) {
            $data = [
                'userinfo'  => $this->auth->getUserinfo(),
                'thirdinfo' => $result
            ];
            $superior_uid =\app\common\model\User::superior_uid($referrer_id);
            if($superior_uid && $superior_uid!=$this->auth->id) \app\common\model\User::update(['superior_uid'=>$superior_uid],['id'=>$this->auth->id]);
            $this->success(__('Logged in successful'), $data);
        }
        $url = url('user/index');
        $this->error(__('Operation failed'), $url);

    }

    /**
     * 获取openid
     */
    public function getOpenid(){
        $params = $this->request->post();
        //file_put_contents('log/weixin_login_notify.txt', json_encode($params) . "\r\n", FILE_APPEND);
        extract($params);
        if(empty($iv)||empty($sessionKey)||empty($encryptedData)){
            $this->error('缺少必要参数');
        }
        if(empty($referrer_id)) $referrer_id=0;
        $referrer_id = (int)$referrer_id;

        $decryptSession = cache($sessionKey);
        if (!$decryptSession || !isset($decryptSession['openid'])) {
            $this->error('未获取到登录态,请重试!');
        }
        //file_put_contents('log/weixin_login_notify.txt', json_encode($decryptSession) . "\r\n", FILE_APPEND);
        $decryptUserInfo = $this->wxapp->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        $decryptUserInfo = array_merge($decryptUserInfo,$decryptSession);

        //组装decryptData
        $decryptData = array_change_key_case($decryptUserInfo, CASE_LOWER); // 将数组中的所有键名修改为小写
        if (empty($decryptData['openid'])) {
            $this->error('code错误,请重试!');
        }
        //file_put_contents('log/weixin_login_notify.txt', json_encode($decryptData) . "\r\n", FILE_APPEND);
        $this->success('openid',['openid'=>$decryptData['openid']]);
    }


}
